package com.ruanmou.house.housecommon.exception;

import com.ruanmou.house.housecommon.common.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Controller
public class ApiErrorExceptionController implements ErrorController {
    public static final String ERROR_PATH="/error";
    @Autowired
    private ErrorAttributes errorAttributes;
    @Override
    public String getErrorPath() {
        return ERROR_PATH;
    }
    @RequestMapping(value = ERROR_PATH,produces = "text/html")
    public String ErrorHandler( HttpServletResponse response){
        int status = response.getStatus();
        switch (status){
            case 403:return "403";
            case 404:return "404";
            case 500:return "500";

        }
        return "error";
    }
    @RequestMapping(ERROR_PATH)
    @ResponseBody
    public ApiResponse ErrorHandler(HttpServletRequest request,HttpServletResponse response){
        ServletWebRequest servletRequest = new ServletWebRequest(request);
        Map<String, Object> errorAttributesMap = this.errorAttributes.getErrorAttributes(servletRequest, false);
        int statusCode=getStatus(response);
        return ApiResponse.ofMessage(statusCode,String.valueOf(errorAttributesMap.getOrDefault("Message","error")));
    }

    private int getStatus(HttpServletResponse response) {
        int code = response.getStatus();
        if(code!=0){
            return code;
        }else{
            return 500;
        }
    }


}
